<template>
  <div class="app-container">
    <template v-if="isLoggedIn">
      <el-container class="main-container">
        <el-aside :width="sidebarWidth" class="app-sidebar-container">
          <app-sidebar />
        </el-aside>
        <el-container class="content-wrapper">
          <el-header height="64px" class="app-header-container">
            <app-header />
          </el-header>
          <div class="tab-container">
            <tab-bar />
          </div>
          <el-main class="app-main-container">
            <!-- 主应用路由视图，仅在非微应用路由时渲染 -->
            <router-view v-slot="{ Component, route }">
              <template v-if="!isMicroAppRoute(route)">
                <transition name="fade" mode="out-in">
                  <keep-alive :include="keepAliveNames">
                    <component 
                      :is="Component" 
                      v-if="!tabStore.reloading" 
                      :key="route.fullPath" 
                    />
                  </keep-alive>
                </transition>
              </template>
            </router-view>
            <!-- 微应用容器，始终存在但根据路由控制显示/隐藏 -->
            <div v-show="isMicroAppRoute($route) && !isReactDevopsRoute($route)" id="subapp-container"></div>
            <!-- react-devops专用容器 -->
            <div v-show="isReactDevopsRoute($route)" id="subapp-viewport"></div>
          </el-main>
          <el-footer height="50px" class="app-footer-container">
            <app-footer />
          </el-footer>
        </el-container>
      </el-container>
    </template>
    <template v-else>
      <router-view />
    </template>
  </div>
</template>

<script setup lang="ts">
import { computed, watchEffect, onMounted, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from './store/user'
import { useAppStore } from './store/app'
import { useTabStore } from './store/tab'
import { isMicroAppPath } from './utils/microAppHelper'
import AppHeader from './components/AppHeader.vue'
import AppSidebar from './components/AppSidebar.vue'
import AppFooter from './components/AppFooter.vue'
import TabBar from './components/TabBar.vue'
import { useUserProfile } from './composables/useUserProfile'
import { ElLoading, ElMessage } from 'element-plus'
import TokenManager from './utils/tokenManager'
import { authCenterApi } from './api/authCenter'

const appStore = useAppStore()
const userStore = useUserStore()
const tabStore = useTabStore()
const router = useRouter()
const route = useRoute()

// 防止重复加载用户信息的标志
const isLoadingUserInfo = ref(false)
// 使用用户个人信息composable
const { fetchUserProfile } = useUserProfile()

const sidebarWidth = computed(() => {
  return appStore.sidebarCollapsed ? '64px' : '220px'
})

const isLoggedIn = computed(() => userStore.isLoggedIn)

const keepAliveNames = computed(() => tabStore.keepAliveNames)

const isMicroAppRoute = (r: any) => isMicroAppPath(r.path)

// 判断是否为react-devops路由
const isReactDevopsRoute = (r: any) => r.path.startsWith('/react-devops')

// 应用初始化时加载用户信息
onMounted(async () => {
  // 只有在有token且用户信息未加载且未处于加载状态时才获取用户信息
  if (isLoggedIn.value && !userStore.getUserInfo.userId && !isLoadingUserInfo.value) {
    isLoadingUserInfo.value = true
    
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '加载用户信息...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    
    try {
      // 使用composable获取用户信息
      await fetchUserProfile()
    } catch (error: any) {
      // 如果是401错误，可能是token过期，尝试刷新token
      if (error.response && error.response.status === 401) {
        const refreshToken = TokenManager.getRefreshToken()
        if (refreshToken) {
          try {
            const refreshResult = await authCenterApi.refreshToken(refreshToken)
            if (refreshResult.code === 200 && refreshResult.data) {
              TokenManager.setTokens(
                refreshResult.data.accessToken,
                refreshResult.data.refreshToken
              )
              userStore.setToken(refreshResult.data.accessToken)
              
              // 重新获取用户信息
              await fetchUserProfile()
            }
          } catch (refreshError) {
            // Token刷新失败，清除登录状态并跳转到登录页
            userStore.logout()
            router.replace('/login')
            ElMessage.error('登录已过期，请重新登录')
          }
        } else {
          // 没有refreshToken，直接清除登录状态
          userStore.logout()
          router.replace('/login')
          ElMessage.error('登录已过期，请重新登录')
        }
      } else {
        // 其他错误，清除登录状态
        userStore.logout()
        router.replace('/login')
        ElMessage.error('登录状态异常，请重新登录')
      }
    } finally {
      loadingInstance.close()
      isLoadingUserInfo.value = false
    }
  }
})
</script>

<style scoped>
.app-container {
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  background-color: var(--background-color);
}

.main-container {
  height: 100%;
  overflow: hidden;
}

.content-wrapper {
  height: 100%;
  overflow: hidden;
  transition: all var(--transition-normal);
}

.app-sidebar-container {
  background: linear-gradient(135deg, var(--primary-color), var(--accent-color));
  transition: width var(--transition-normal);
  box-shadow: var(--shadow-md);
  z-index: 10;
  overflow: hidden;
}

.app-header-container {
  background: var(--card-background-color);
  padding: 0;
  height: 64px;
  z-index: 9;
}

.tab-container {
  background: var(--card-background-color);
  border-bottom: 1px solid var(--border-color-light);
  z-index: 8;
}

.app-main-container {
  background-color: var(--background-color);
  height: calc(100vh - 154px);
  overflow-y: auto;
  transition: all var(--transition-normal);
}
.el-main.app-main-container {
  --el-main-padding:0;
  padding: none !important;
}
.app-footer-container {
  background-color: var(--card-background-color);
  color: var(--text-color-secondary);
  text-align: center;
  border-top: 1px solid var(--border-color-light);
  height: 50px;
}

#subapp-container {
  margin-top: 24px;
  background: var(--card-background-color);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-md);
  min-height: 300px;
  overflow: hidden;
  transition: all var(--transition-normal);
}

#subapp-viewport {
  margin-top: 24px;
  background: var(--card-background-color);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-md);
  min-height: 300px;
  overflow: hidden;
  transition: all var(--transition-normal);
}

/* 页面过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style> 